
#include <stdio.h>
#include <map>
#include <string.h>
#include <iostream>
#include <fstream>
#include <dlfcn.h>
#include <stdlib.h>
#include <map>
#include <sys/stat.h>
#include <sys/time.h>

#include "DynLib.h"

using namespace std;

DynLib::DynLib(const char *libraryName) {

    if (libraryName==NULL || strlen(libraryName)==0) {
        cerr << "NULL or empty library name passed to DynLib constructor" << endl;
        return;
    }

    struct stat stFileInfo;
    if (0 != stat(libraryName,&stFileInfo)) {
        cerr << "Invalid library name '" << libraryName << "' passed to DynLib constructor" << endl;
        return;
    }

    lib_handle = dlopen(libraryName, RTLD_LAZY | RTLD_LOCAL);
    if (NULL == lib_handle) {
        char *error = dlerror();
        cerr << "Failed to load dynamic library '" << libraryName << "' - dlerror() returned " << (error==NULL?"NULL":error) << endl;
    }
}

DynLib::~DynLib() {
}

void *DynLib::get_function(const char *functionName) {

#ifdef DEBUG
    cerr << "get_function(" << functionName << ")" << endl;
#endif

	if (NULL == lib_handle) {
		cerr << "Library not loaded";
		return NULL;
	}

	void *func = functionMap[functionName];
	if (func==NULL) {
		func = dlsym(lib_handle, functionName);
		if (!func) {
            char *error = dlerror();
			cerr << "Failed to resolve function '" << functionName << "' - dlerror() returned " << (error==NULL?"NULL":error) << endl;
			return NULL;
		}
		functionMap[functionName] = func;
	}

	return func;
}

